package a66weding.com.jiehuntong.activity.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.CategorySearchActivity;
import a66weding.com.jiehuntong.activity.home.adapter.ForSearchAdapter;
import a66weding.com.jiehuntong.activity.home.adapter.ForSearchLvAdapter;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CaseBean;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.ForSearchBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.SharesUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.dao.record.RecordBean;
import a66weding.com.jiehuntong.dao.record.RecordDao;
import a66weding.com.jiehuntong.dao.record.RecordOpenHelper;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.EditTextWithAutoClear;
import a66weding.com.jiehuntong.widgets.NoScrollGridView;

/**
 * Created by admin on 2016/8/9.
 * 搜索界面
 */
public class ForSearchActivity extends Activity implements OnNetResultListener,AdapterView.OnItemClickListener ,View.OnClickListener{
    private ForSearchBean  caseBean;
    private ForSearchAdapter adapter;
    private NoScrollGridView noScrollGridView;
    private List<ForSearchBean.DataBean> caseBeenlist;
    private RelativeLayout mBackLay;
    //数据库
    private RecordDao recordDao;
    //会员id;
    private int memberId;
    //输入框
    private EditTextWithAutoClear editTextWithAutoClear;
    //
    private ListView lv;
    private ForSearchLvAdapter forSearchLvAdapter;
    private View itemDelet;
    private TextView delet_tv;
    private String keyword;

    private boolean isLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_for_search);

        isLogin  = ((GlobalApplication)getApplication()).isLogin();
        if(isLogin) {
            memberId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        }

        recordDao = new RecordDao(this);

        initView();
    }
    
    private  void  initView(){
        findViewById(R.id.cate_title).setVisibility(View.INVISIBLE);
        lv = (ListView) findViewById(R.id.for_search_lv);
        noScrollGridView = (NoScrollGridView) findViewById(R.id.for_search_gridview);
        mBackLay = (RelativeLayout) findViewById(R.id.rlay_back);

        adapter = new ForSearchAdapter(this,null);
        noScrollGridView.setAdapter(adapter);
        noScrollGridView.setOnItemClickListener(this);
        editTextWithAutoClear = (EditTextWithAutoClear) findViewById(R.id.cate_search);
        forSearchLvAdapter =new ForSearchLvAdapter(this,null);
        lv.setAdapter(forSearchLvAdapter);
        itemDelet = View.inflate(this,R.layout.item_delete_forsearch,null);
        delet_tv = (TextView) itemDelet.findViewById(R.id.item_delet_tv);
        delet_tv.setOnClickListener(this);
        lv.addFooterView(itemDelet);

        mBackLay.setOnClickListener(this);
        editTextWithAutoClear.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH) {
// 先隐藏键盘
                    ((InputMethodManager) editTextWithAutoClear.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    keyword = editTextWithAutoClear.getText().toString();
                    //存储数据
                    recordDao.add(""+memberId, keyword);
                    //上传服务器;
                    upKeyword();
                    Intent intent = new Intent(ForSearchActivity.this, CategorySearchActivity.class);
                    if (keyword.toString().contains(" ")) {
                        Toast.makeText(ForSearchActivity.this,"请不要输入空格",Toast.LENGTH_SHORT).show();
                        return false;
                    } else if (keyword.toString().isEmpty()) {
                        Toast.makeText(ForSearchActivity.this,"请输入搜索内容",Toast.LENGTH_SHORT).show();
                        return false;
                    } else {
                        intent.putExtra("searchinfo",keyword);
                        startActivity(intent);
                        return true;
                    }
                }
                return false;
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        getHot();
       List<RecordBean> list =  recordDao.findAll();
        forSearchLvAdapter.clear();
        forSearchLvAdapter.append(list);
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof ForSearchBean){
            caseBean = (ForSearchBean) data;
            switch (caseBean.getResCode()){
                case "0000":
                    adapter.clear();
                    caseBeenlist = caseBean.getData();
                    adapter.append(caseBeenlist);
                    break;
            }
        }
        if (data instanceof  CommonResultBean){
            CommonResultBean bean = (CommonResultBean) data;
            switch (bean.getResCode()){
                case "0000":
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    /**
     * 获取热门接口;
     * GET WeddingMobileApi/get_HotSearch?Token={Token}
     返回热门搜索，共9条数据
     */
    private void getHot(){
        String url = Url.GET_HOTSEARCH;
        HttpRequestBean RequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,this, ForSearchBean.class,RequestCode.GET_CASESLISTBYSEARCH );
        HttpHandleUtil.executeCommonGet(this,RequestBean);

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(ForSearchActivity.this, CategorySearchActivity.class);
        intent.putExtra("searchinfo",caseBeenlist.get(position).getKeywords());
        SharesUtils.getInstance(ForSearchActivity.this).writeXML("search",caseBeenlist.get(position).getKeywords());
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.item_delet_tv:
                recordDao.delete(""+memberId);
                forSearchLvAdapter.clear();
                break;
            case R.id.rlay_back:
                finish();
                break;
        }
    }

    /**
     * POST WeddingMobileApi/post_SearchCreate?Token={Token}&keywords={keywords}
     搜索关键字记录
     */
    private void upKeyword(){
       String url =  Url.POST_SEARCHCREATE+"keywords="+ keyword;
        HashMap hashMap = new HashMap();
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, CommonResultBean.class, RequestCode.ADDTYPEWEDDINGPROCESS,hashMap);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }

}
